/**
 * Copyright (C) 2012  The CFuture Android SDK Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lurencun.android.toolkit.network;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-15
 */
public class UploadTask {

	private final static String TAG = "UploadTask";
	private UploadTaskListener mListener;

	/**
	 * 设置回调
	 * 
	 * @param listener
	 */
	public void setTaskListener(UploadTaskListener listener) {
		mListener = listener;
	}

	/**
	 * 向URL发送位数据
	 * 
	 * @param postUrl
	 * @param data
	 */
	public void post(String postUrl, byte[] data) {
		try {
			URL url = new URL(postUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-length", "" + data.length);
			httpConn.setRequestProperty("Content-Type","application/octet-stream");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");
			OutputStream outputStream = httpConn.getOutputStream();
			outputStream.write(data);
			outputStream.close();
			if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
				if (null != mListener)mListener.onComplete();
			}else{
				if (null != mListener) mListener.onFailed("服务器响应非成功状态！");
			}
			
		} catch (MalformedURLException e) {
			Log.e(TAG, "==>解析URL错误：" + e.getMessage());
			if (null != mListener) mListener.onFailed("解析URL错误！");
		} catch (IOException e) {
			Log.e(TAG, "==>连接IO错误：" + e.getMessage());
			if (null != mListener) mListener.onFailed("连接IO错误！");
		}

	}
}
